//
//  SMCalendarPicker.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/12.
//

import SwiftUI

struct SMCalendarPicker: View {
    
    // MARK: - 属性
    @State private var selectedDate: Date
    
    // MARK: - 数据
    @State private var years: [Int] = []
    @State private var months: [Int] = Array(1...12)
    @State private var days: [Int] = []
    
    @State private var selectedYear: Int = 0
    @State private var selectedMonth: Int = 0
    @State private var selectedDay: Int = 0
    
    private var onDateSelected: ((Date) -> Void)?
    
    // MARK: - 初始化
    init(selectedDate: Date, onDateSelected: ((Date) -> Void)?) {
        self._selectedDate = State(initialValue: selectedDate)
        self.onDateSelected = onDateSelected
    }
    
    // MARK: - UI
    var body: some View {
        VStack(spacing: 0) {
            Spacer()
                .frame(height: 25)
            titleView
                .ignoresSafeArea()
            Spacer()
                .frame(height: 15)
            columnsContainer
                .ignoresSafeArea()
            Spacer()
                .frame(height: 5)
            confirmButton
                .padding(.bottom, bottomSafeArea)
        }
        .background(Color.clear)
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.1), radius: 10, x: 0, y: 2)
        .onAppear {
            setupData()
        }
    }
    
    private var titleView: some View {
        Text("Date Selection")
            .font(.system(size: 18, weight: .medium))
            .frame(maxWidth: .infinity, alignment: .center)
            .padding(.bottom, 16)
    }
    
    private var columnsContainer: some View {
        VStack(spacing: 0) {
            // 列标题
            HStack(spacing: 0) {
                Text("Day")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(.black)
                    .frame(maxWidth: .infinity)
                
                Text("Month")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(.black)
                    .frame(maxWidth: .infinity)
                
                Text("Year")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(.black)
                    .frame(maxWidth: .infinity)
            }
            .frame(height: 30)
            .padding(.bottom, 10)
            
            // 列内容
            HStack(spacing: 0) {
                // 日列
                dayColumn
                    .frame(maxWidth: .infinity)
                
                // 分隔线
                Rectangle()
                    .fill(Color(.systemGray5))
                    .frame(width: 1)
                
                // 月列
                monthColumn
                    .frame(maxWidth: .infinity)
                
                // 分隔线
                Rectangle()
                    .fill(Color(.systemGray5))
                    .frame(width: 1)
                
                // 年列
                yearColumn
                    .frame(maxWidth: .infinity)
            }
        }
        .padding(.bottom, 0)
    }
    
    private var dayColumn: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(spacing: 0) {
                    ForEach(days, id: \.self) { day in
                        dayCell(day: day)
                            .id(day)
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    withAnimation {
                        proxy.scrollTo(selectedDay, anchor: .center)
                    }
                }
            }
            .onChange(of: selectedDay) { newValue in
                withAnimation {
                    proxy.scrollTo(newValue, anchor: .center)
                }
            }
        }
    }
    
    private var monthColumn: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(spacing: 0) {
                    ForEach(months, id: \.self) { month in
                        monthCell(month: month)
                            .id(month)
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    withAnimation {
                        proxy.scrollTo(selectedMonth, anchor: .center)
                    }
                }
            }
            .onChange(of: selectedMonth) { newValue in
                withAnimation {
                    proxy.scrollTo(newValue, anchor: .center)
                }
            }
        }
    }
    
    private var yearColumn: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(spacing: 0) {
                    ForEach(years, id: \.self) { year in
                        yearCell(year: year)
                            .id(year)
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    withAnimation {
                        proxy.scrollTo(selectedYear, anchor: .center)
                    }
                }
            }
            .onChange(of: selectedYear) { newValue in
                withAnimation {
                    proxy.scrollTo(newValue, anchor: .center)
                }
            }
        }
    }
    
    private var confirmButton: some View {
        Button(action: confirmSelection) {
            Text("Confirm")
                .font(.system(size: 16, weight: .medium))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .frame(height: 44)
                .background(Color.blue)
                .cornerRadius(22)
        }
    }
    
    // MARK: - 单元格视图
    private func dayCell(day: Int) -> some View {
        Text("\(day)")
            .font(.system(size: 16))
            .foregroundColor(day == selectedDay ? .black : Color(hex: "#999999"))
            .frame(height: 30)
            .frame(maxWidth: .infinity)
            .background(day == selectedDay ? Color(hex: "#FFEEC5") : Color.clear)
            .cornerRadius(15)
            .padding(.horizontal, 10)
            .onTapGesture {
                selectedDay = day
            }
    }
    
    private func monthCell(month: Int) -> some View {
        Text("\(month)")
            .font(.system(size: 16))
            .foregroundColor(month == selectedMonth ? .black : Color(hex: "#999999"))
            .frame(height: 30)
            .frame(maxWidth: .infinity)
            .background(month == selectedMonth ? Color(hex: "#FFEEC5") : Color.clear)
            .cornerRadius(15)
            .padding(.horizontal, 10)
            .onTapGesture {
                selectedMonth = month
                updateDays()
            }
    }
    
    private func yearCell(year: Int) -> some View {
        Text(String(year))
            .font(.system(size: 16))
            .foregroundColor(year == selectedYear ? .black : Color(hex: "#999999"))
            .frame(height: 30)
            .frame(maxWidth: .infinity)
            .background(year == selectedYear ? Color(hex: "#FFEEC5") : Color.clear)
            .cornerRadius(15)
            .padding(.horizontal, 10)
            .onTapGesture {
                selectedYear = year
                updateDays()
            }
    }
    
    // MARK: - 数据方法
    private func setupData() {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day], from: selectedDate)
        
        selectedYear = components.year ?? 1990
        selectedMonth = components.month ?? 1
        selectedDay = components.day ?? 1
        
        // 生成年份范围 (当前年份往前120年)
        let currentYear = calendar.component(.year, from: Date())
        years = Array((currentYear-120)...currentYear)
        
        // 生成当月天数
        updateDays()
    }
    
    private func updateDays() {
        let calendar = Calendar.current
        let dateComponents = DateComponents(year: selectedYear, month: selectedMonth)
        if let date = calendar.date(from: dateComponents),
           let range = calendar.range(of: .day, in: .month, for: date) {
            days = Array(range.lowerBound..<range.upperBound)
        } else {
            days = Array(1...31)
        }
        
        // 确保选中的日期有效
        if selectedDay > days.count {
            selectedDay = days.count
        }
    }
    
    // MARK: - 操作
    private func confirmSelection() {
        let calendar = Calendar.current
        if let date = calendar.date(from: DateComponents(
            year: selectedYear,
            month: selectedMonth,
            day: selectedDay
        )) {
            selectedDate = date // 直接更新 Binding
            onDateSelected?(date)
        }
    }
}

